package com.htstar.ovms.enterprise.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.htstar.ovms.admin.api.entity.SysUser;
import com.htstar.ovms.admin.api.feign.SysUserFeign;
import com.htstar.ovms.common.core.i18n.MsgCode;
import com.htstar.ovms.common.core.util.OvmDateUtil;
import com.htstar.ovms.common.core.util.R;
import com.htstar.ovms.common.excel.util.ExcelWriter;
import com.htstar.ovms.common.log.annotation.SysLog;
import com.htstar.ovms.common.security.service.OvmsUser;
import com.htstar.ovms.common.security.util.SecurityUtils;
import com.htstar.ovms.device.api.entity.Device;
import com.htstar.ovms.device.api.entity.DeviceSim;
import com.htstar.ovms.device.api.vo.DeviceImportVO;
import com.htstar.ovms.device.api.vo.ImportVO;
import com.htstar.ovms.enterprise.api.dto.CarFuelCardDto;
import com.htstar.ovms.enterprise.api.entity.CarFuelCard;
import com.htstar.ovms.enterprise.api.entity.CarInfo;
import com.htstar.ovms.enterprise.api.req.CarFileManageReq;
import com.htstar.ovms.enterprise.api.req.RechargeReq;
import com.htstar.ovms.enterprise.api.vo.FuelCardPageVO;
import com.htstar.ovms.enterprise.service.CarFuelCardService;
import com.htstar.ovms.enterprise.service.CarInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.DecimalFormat;
import java.util.*;


/**
 * 油卡
 *
 * @author lw
 * @date 2020-06-23 13:54:59
 */
@RestController
@AllArgsConstructor
@RequestMapping("/carfuelcard")
@Api(value = "carfuelcard", tags = "油卡管理")
@Slf4j
public class CarFuelCardController {

    private final CarFuelCardService carFuelCardService;

    private final CarInfoService carInfoService;

    private final SysUserFeign sysUserFeign;

    /**
     * 分页查询
     *
     * @param carFileManageReq
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @PostMapping("/queryPage")
    public R<IPage<FuelCardPageVO>> queryPage(@RequestBody CarFileManageReq carFileManageReq) {
        return R.ok(carFuelCardService.queryPage(carFileManageReq));
    }


    /**
     * 通过id查询油卡
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(carFuelCardService.getById(id));
    }

    /**
     * 新增油卡
     *
     * @param carFuelCard 油卡
     * @return R
     */
    @ApiOperation(value = "新增油卡", notes = "新增油卡")
    @SysLog("新增油卡")
    @PostMapping
    //@PreAuthorize("@pms.hasPermission('enterprise_carfuelcard_add')" )
    public R save(@RequestBody CarFuelCard carFuelCard) {

        return carFuelCardService.saveInfo(carFuelCard);
    }

    /**
     * 修改油卡
     *
     * @param carFuelCard 油卡
     * @return R
     */
    @ApiOperation(value = "修改油卡", notes = "修改油卡")
    @SysLog("修改油卡")
    @PutMapping
    public R updateById(@RequestBody CarFuelCard carFuelCard) {
        return carFuelCardService.updateFuelById(carFuelCard);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return R
     */
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @SysLog("批量删除")
    @DeleteMapping("/{ids}")
    public R removeById(@PathVariable String ids) {
        return carFuelCardService.removeByIds(ids);
    }

    /**
     * 导出
     *
     * @param
     * @param
     */
    @ApiOperation(value = "导出", notes = "导出")
    @PostMapping("/export")
    public void exportExcel(@RequestBody CarFileManageReq req) {
        carFuelCardService.exportExcel(req);
    }

    @ApiOperation(value = "油卡充值", notes = "油卡充值")
    @SysLog("油卡充值")
    @PostMapping("/recharge")
    public R recharge(@RequestBody RechargeReq recharge) {
        return carFuelCardService.recharge(recharge);
    }

    public List<String> getDuplicateElements(List<CarFuelCardDto> list, boolean flag, Integer s) {
        int count = 0;// 默认出现的次数为1
        List<String> collect = new ArrayList<>();
        int size = list.size();
        List<Integer> integers = new ArrayList<>();//计算下标添加到list
        Set<String> hashSet = new HashSet<>();//去重复
        if (Objects.equals(s, 1)) {
            for (int i = 0; i < size; i++) {
                CarFuelCardDto carFuelCardDto = list.get(i);
                if (!hashSet.contains(carFuelCardDto.getCardNo())) {
                    integers.clear();
                    for (int j = i + 1; j < size; j++) {//与下一条对比
                        CarFuelCardDto carFuelCardDtos = list.get(j);
                        if (Objects.equals(carFuelCardDto.getCardNo(), carFuelCardDtos.getCardNo())) {
                            hashSet.add(carFuelCardDtos.getCardNo());
                            count++;//累加重复次数
                            integers.add((j + 2));
                        }
                    }
                    String finalStar = StringUtils.join(integers, ",");
                    if (count > 0) {//大于0说明上一条与下一条比较发型不是重复，则不用累加
                        collect.add("重复油卡卡号是：" +
                                carFuelCardDto.getCardNo() + "重复了" + count + "条--依次出现在" + finalStar + "行");
                        count = 0;//重新累加下一条
                    }

                }
            }
        }
        return collect;
    }

    /**
     * 导入油卡信息
     *
     * @param file
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "导入设备信息", notes = "导入设备信息")
    @SysLog("导入油卡信息")
    @PostMapping("/importFuelCardInfo")
    @Transactional(rollbackFor = Exception.class)
    public R importSimInfo(@RequestParam(value = "file") MultipartFile file) {
        boolean flag = true;
        List<CarFuelCard> list = new ArrayList<>();
        List<DeviceSim> lists = new ArrayList<>();
        List<String> vos = new ArrayList<>();
        CarFuelCardDto carFuelCard = null;
        DeviceImportVO a = null;
        List<CarFuelCardDto> carFuelCards = ExcelWriter.onlyOneHeadingImport(file, CarFuelCardDto.class);
        if (!CollectionUtils.isEmpty(carFuelCards)) {
            for (int i = 0; i < carFuelCards.size(); i++) {
                CarFuelCard card = new CarFuelCard();
                carFuelCard = carFuelCards.get(i);
                if (!StringUtils.isNotBlank(carFuelCard.getCardNo())) {
                    flag = false;
                    vos.add("第" + (i + 2) + "行油卡卡号为空,导入失败，请更改正确再试");
                    //return R.failed("第" + (i + 1) + "行设备编号为空,导入失败，请更改正确再试");
                }
                if (!StringUtils.isNotBlank(carFuelCard.getCardName())) {
                    flag = false;
                    vos.add("第" + (i + 2) + "行油卡卡名为空,导入失败，请更改正确再试");
                    //return R.failed("第" + (i + 1) + "行设备编号为空,导入失败，请更改正确再试");
                }
                int count = carFuelCardService.count(new QueryWrapper<CarFuelCard>()
                        .lambda().eq(CarFuelCard::getCardNo, carFuelCard.getCardNo()).eq(CarFuelCard::getDelFlag, 0));
                if (count != 0) {
                    a = new DeviceImportVO();
                    flag = false;
                    vos.add("第" + (i + 2) + "行油卡卡号数据库已经存在,导入失败，请更改正确再试");
                    //return R.failed("第" + (i + 1) + "行设备编号数据库已经存在,导入失败，请更改正确再试");
                }
                card.setEtpId(SecurityUtils.getUser().getEtpId());
                if (Objects.equals(carFuelCard.getBindingTypeName(), "车辆")) {
                    CarInfo one = carInfoService.getOne(new LambdaQueryWrapper<CarInfo>()
                            .eq(CarInfo::getLicCode, carFuelCard.getBindingName()).eq(CarInfo::getDelFlag, 0));
                    card.setBindingType(1);
                    if (Objects.equals(one, null)) {
                        flag = false;
                        vos.add("第" + (i + 2) + "数据库没有该车辆" + carFuelCard.getBindingName() + "信息,导入失败，请更改正确再试");
                    } else if (!Objects.equals(one, null)) {
                        int count1 = carFuelCardService.count(new LambdaQueryWrapper<CarFuelCard>()
                                .eq(CarFuelCard::getBindingId, one.getId()).eq(CarFuelCard::getBindingType, 1));
                        if (count1 > 0) {
                            flag = false;
                            vos.add("第" + (i + 2) + "已有油卡绑定该车辆" + carFuelCard.getBindingName() + "信息,导入失败，请更改正确再试");
                        } else if (Objects.equals(one.getEtpId(), SecurityUtils.getUser().getEtpId())) {
                            flag = false;
                            vos.add("第" + (i + 2) + "该车辆" + carFuelCard.getBindingName() + "不是本企业,导入失败，请更改正确再试");
                        } else {
                            card.setBindingId(one.getId());
                        }
                    }
                } else if (Objects.equals(carFuelCard.getBindingTypeName(), "人员")) {
                    card.setBindingType(3);
                    SysUser one = sysUserFeign.getUser(carFuelCard.getBindingName());
                    if (Objects.equals(one, null)) {
                        flag = false;
                        vos.add("第" + (i + 2) + "数据库没有该人员" + carFuelCard.getBindingName() + "信息,导入失败，请更改正确再试");
                    } else if (!Objects.equals(one, null)) {
                        int count1 = carFuelCardService.count(new LambdaQueryWrapper<CarFuelCard>()
                                .eq(CarFuelCard::getBindingId, one.getUserId()).eq(CarFuelCard::getBindingType, 1));
                        if (count1 > 0) {
                            flag = false;
                            vos.add("第" + (i + 2) + "已有油卡绑定该人员" + carFuelCard.getBindingName() + "信息,导入失败，请更改正确再试");
                        } else if (Objects.equals(one.getEtpId(), SecurityUtils.getUser().getEtpId())) {
                            flag = false;
                            vos.add("第" + (i + 2) + "该人员" + carFuelCard.getBindingName() + "不是本企业,导入失败，请更改正确再试");
                        } else {
                            card.setBindingId(one.getUserId());
                        }
                    }


                }
                if (!Objects.equals(carFuelCard.getBindingTypeName(), null)) {
                    if (!Objects.equals(carFuelCard.getBindingTypeName(), "人员")
                            || !Objects.equals(carFuelCard.getBindingTypeName(), "车辆")) {
                        flag = false;
                        vos.add("第" + (i + 2) + "只能是人员和车辆类型,导入失败，请更改正确再试");
                    }
                }

                card.setCardNo(carFuelCard.getCardNo());
                card.setCardName(carFuelCard.getCardName());
                card.setCardUser(carFuelCard.getCardUser());
                card.setMobile(carFuelCard.getMobile());
                double v = carFuelCard.getCardBalance() * 100;//数据库存的分，所有要转*10000
                int b = (int) v; //double 转int存入Integer
                card.setCardBalance(b);
                list.add(card);

            }
            List<String> duplicateValue = getDuplicateElements(carFuelCards, flag, 1);
            //List<DeviceImportVO> duplicateValues= getDuplicateElements(carFuelCards, flag,2);
            if (duplicateValue.size() > 0) {


                for (String s : duplicateValue) {
                    flag = false;
                    vos.add(s);
                }

            }
            if (flag) {
                flag = carFuelCardService.saveBatch(list);
                //deviceSimService.updateBatchById(lists);
                return R.ok(flag);
            }
        } else {
            return R.failed(MsgCode.OIL_CARD_TEMPLATE_EMPTY.msg());
        }
        DeviceImportVO v = new DeviceImportVO();
        List<ImportVO> i = new ArrayList<>();
        vos.forEach(s -> {
            ImportVO va = new ImportVO();
            va.setName(s);
            i.add(va);
        });
        v.setError(i);

        return R.faileds(v, MsgCode.MAKECHANGESWHILEIMPORTING.msg());
    }


}

